<template>
  <div>
    <div>
      <a-button type="primary" @click="visible = true">导入</a-button>
    </div>
      <a-form :form="form">
    <a-form-item :label="field" v-for="field in fields" :key="field">
      <a-input v-decorator="[field]"></a-input>
    </a-form-item>
    <a-form-item>
      <a-button type="primary" @click="submit">添加</a-button>
    </a-form-item>
  </a-form>
    <a-modal :visible="visible" title="导入" @ok="handleImport" @cancel="visible = false">
      <a-form>
        <a-form-item label="书源代码">
          <a-textarea v-model="code" :row="10"></a-textarea>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import { getSource, addSource } from '@/api'
export default {
  data () {
    return {
      detail: {},
      visible: false,
      code: '',
      form: this.$form.createForm(this),
      fields: ["bookSourceGroup", "bookSourceName", "bookSourceType", "bookSourceUrl", "enable", "httpUserAgent", "ruleBookAuthor", "ruleBookContent", "ruleBookName", "ruleChapterList", "ruleChapterName", "ruleChapterUrl", "ruleChapterUrlNext", "ruleContentUrl", "ruleContentUrlNext", "ruleCoverUrl", "ruleFindUrl", "ruleIntroduce", "ruleSearchAuthor", "ruleSearchCoverUrl", "ruleSearchKind", "ruleSearchLastChapter", "ruleSearchList", "ruleSearchName", "ruleSearchNoteUrl", "ruleSearchUrl", "serialNumber", "weight"]
    }
  },
  methods: {
    handleImport () {
      if (!this.code) {
        this.$message.error('请输入代码')
        return
      }
      let code
      try {
        code = JSON.parse(this.code)
      } catch (e) {
        this.$message.error('请输入正确的JSON')
      }
      if (code) {
        this.form.setFieldsValue(code)
        this.visible = false
      }
    },
    submit () {
      this.form.validateFields(async (err, values) => {
        if (err) return
        const result = await getSource({ bookSourceUrl: values.bookSourceUrl })
        if (result) {
          this.$message.error('书源已存在')
          return
        }
        await addSource(values)
        this.$router.push('/source/list')
      })
    }
  }
}
</script>

<style>

</style>